package vip.xls8z.learning.nio.reactor.multiple.reactor;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Acceptor implements Runnable {

    int next = 0;
    final Selector[] selectors;
    final ServerSocketChannel serverSocketChannel;

    public Acceptor(Selector[] selectors, ServerSocketChannel serverSocketChannel) {
        this.selectors = selectors;
        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public synchronized void run() {
        try {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                socketChannel.configureBlocking(false);
                // 选个 Reactor 去负责接处理收到的连接
                new Handler(selectors[next], socketChannel);
            }
            if (++next == selectors.length) next = 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
